package com.aacar.op.service.coupon;


import com.aacar.op.dao.coupon.CouponDao;
import com.aacar.op.entity.coupon.Coupon;
import com.aacar.op.utils.DateUtil;
import com.aacar.op.utils.web.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.helper.DataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("couponService")
@Transactional
public class CouponServiceImpl implements CouponService {
	
	private static Logger logger = LoggerFactory.getLogger(CouponServiceImpl.class);
	
    @Autowired
    private CouponDao couponDao;

	@Override
	public Coupon get(Long id) {
		return couponDao.findOne(id);
	}


	@Override
	public int saveOrUpdate(Coupon entity){
		return 0;
	}

	@Override
	public int delete(Long id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public PageInfo<Coupon> getPage(Map<String, Object> params, Pageable pageable) {
		PageUtils.mergeSort(params, pageable);
        //pageNum(页码)从1开始,spring data common domain从0开始的.
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Coupon> pageContent = couponDao.findAll(params);
        return new PageInfo(pageContent);
	}

	@Override
	public List<Coupon> findCoupons(Coupon entity) {
		Map param = new HashMap();
		param.put("batchName", entity.getBatchName());
		param.put("couponNo",entity.getCouponNo());
		param.put("couponStatus",entity.getCouponStatus());
		List<Coupon> list = couponDao.findAll(param);
		return list;
	}

	@Override
	public List<Coupon> findGroupByBatchName(Coupon entity) {
		List<Coupon> all = couponDao.findGroupByBatchName("");
		return all;
	}

	@Override
	public Boolean validateBatchName(String batchName) {
		List<Coupon> list = couponDao.findCouponsByBatchName(batchName);
		if(list!=null&&list.size()>0){
			return false;
		}
		return true;
	}

	@Override
	public void saveBatchCoupon(Coupon coupon) {
		List<Coupon> coupons = new ArrayList<>();
		for(int i=1;i<=coupon.getCouponNum();i++){
			Coupon couponParam = new Coupon();

			String couponNo = DateUtil.date2Str(DateUtil.defaultPattern4,DateUtil.getNowDate())
					+ StringUtils.leftPad(String.valueOf(i),3, "0")
					+coupon.getCouponAmount();
			couponNo = couponNo.substring(11);
			couponParam.setCouponNo(couponNo);
			couponParam.setCouponPwd(String.valueOf(new Random().nextInt(999999)));
			couponParam.setBatchName(coupon.getBatchName());
			couponParam.setCouponAmount(coupon.getCouponAmount());
			coupons.add(couponParam);
		}
		couponDao.addBatchInsert(coupons);


	}


}
